"use client"

import React, {useState} from 'react';
import {Button} from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from '@/components/ui/dialog';
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';
import {useRouter} from 'next/navigation';
import {toast} from "sonner"

export function CommentDialog() {
    const [open, setOpen] = useState(false);
    const [comment, setComment] = useState('');
    const router = useRouter();

    const handleSubmit = async (e: React.FormEvent) =>
    {
        e.preventDefault();

        try {
            const response = await fetch("/api/comments", {
                method: "POST",
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify({text: comment}),
            })

            if (!response.ok) {
                throw new Error("提交失败")
            }

            toast("评论提交成功")
            setOpen(false);
            router.refresh()

            setComment('')
        } catch (error) {
            toast("提交评论时出错")
        }
    }

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild>
                <Button variant="outline">添加评论</Button>
            </DialogTrigger>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>添加新评论</DialogTitle>
                </DialogHeader>
                <form onSubmit={handleSubmit} className="space-y-4">
                    <div className="space-y-2">
                        <Label htmlFor="comment">评论内容</Label>
                        <Input
                            id="comment"
                            value={comment}
                            onChange={(e) => setComment(e.target.value)}
                            required
                        />
                    </div>
                    <Button type="submit">提交</Button>
                </form>
            </DialogContent>
        </Dialog>
    )
}